from flask.ext.sqlalchemy import SQLAlchemy
from datetime import datetime
from . import app
db = SQLAlchemy()
db.init_app(app)

class Mixin:
    def save(self):
        db.session.add(self)
        db.session.commit()
        return self

    def delete(self):
        db.session.delete(self)
        db.session.commit()
        return self

class User(db.Model, Mixin):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(120), nullable=False)
    bio = db.Column(db.String(256), default='here is your bio')
    post = db.relationship('Post', backref = 'author', lazy='dynamic')

    def __init__(self, form):
        self.username = form['username']
        self.email = form['email']
        self.password = form['password']

    def __repr__(self):
        return 'User %r' % self.username

    #def is_authenticated(self):
    #    return True

    #def is_active(self):
    #    return True

    #def is_anonymous(self):
    #    return False

    #def get_id(self):
    #    return unicode(self.id)

    def avatar(self, size):
        return 'http://www.gravatar.com/avatar/' + md5(self.email).hexdigest() + '?d=mm&s=' + str(size)

class Tag(db.Model, Mixin):
    __tablename__ = 'tag'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128), default='default_tag', nullable=False)
    post = db.relationship('Post', backref = 'tag', lazy='dynamic')

class Post(db.Model, Mixin):
    __tablename__ = 'post'
    id = db.Column(db.Integer, primary_key=True)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    tag_id = db.Column(db.Integer, db.ForeignKey('tag.id'))

    title = db.Column(db.String(256), nullable=False)
    content = db.Column(db.Text)
    
    hits_count = db.Column(db.Integer, default=0)
    reply_count = db.Column(db.Integer, default=0)
    
    create_at = db.Column(db.DateTime, default=datetime.utcnow) 
    update_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
